package org.zjx.swing.controller;

import org.zjx.entity.LiterateSubScreenBean;
import org.zjx.swing.bean.ColorRecord;
import org.zjx.swing.bean.FontFilePath;
import org.zjx.swing.bean.WordBean;
import org.zjx.swing.model.LiterateModel;
import org.zjx.swing.view.LiterateView;
import org.zjx.util.FileUtil;
import org.zjx.util.ImageUtil;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LiterateController {
    private LiterateView view;
    private LiterateModel model;

    public LiterateController(LiterateView view, LiterateModel model) {
        this.view = view;
        this.model = model;

        view.setColorListRenderer(model);

        // 初始化视图数据
        view.setSubScreenComboBox(model.getSubScreenBeans(), new SubScreenComboBoxListener());
        // 设置按钮监听器
        view.addCaptureConfirmButtonListener(new CaptureConfirmButtonListener());
        view.addScreenButtonListener(new ScreenButtonListener());
        view.addFontFilePath(new AddFontFilePathListener());
        view.deleteFontFilePath(new DeleteFontFilePathListener());
        view.setFontFilePathViewInteraction(new FontFilePathViewInteraction());
        view.setColorListViewInteraction(new FontColorListViewInteraction());
        view.addColorListValue(new AddColorListListener());
        view.deleteColorList(new DeleteColorListListener());
        view.setRecognizeListener(new RecognizeButtonListener());
        view.addIdentifyButtonListener(new IdentifyButtonListener());
        view.addPreviousButtonListener(new PreviousButtonListener());
        view.addNextButtonListener(new NextButtonListener());
        view.addMergeButtonListener(new MergeButtonListener());
        view.addOkButtonListener(new OkButtonListener());
        view.setCaptureButtonListener(new CaptureButtonListener());
    }

    private class IdentifyButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            WordBean wordBean = null;
            try {
                model.setFontHeight(view.getFontHeight());
                wordBean = model.recognizeImage();
            } catch (Exception ex) {
                view.showJOptionPane("识别出错！");
                return;
            }
            if (wordBean == null) {
                view.showJOptionPane("识别失败");
                return;
            }
            view.setMatrixView(wordBean);
            view.setIdentifyAreaValue(model.getWordBeanName(wordBean));
            System.out.println(System.currentTimeMillis() + "自动识别");
        }
    }

    private class PreviousButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            WordBean wordBean = null;
            try {
                wordBean = model.prevWord();
            } catch (Exception ex) {
                view.showJOptionPane("已经到顶了！");
                return;
            }
            if (wordBean == null) {
                view.showJOptionPane("识别失败");
                return;
            }

            view.setMatrixView(wordBean);
            view.setIdentifyAreaValue(model.getWordBeanName(wordBean));
            System.out.println(System.currentTimeMillis() + "上一个识别");
        }
    }

    private class NextButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            WordBean wordBean = null;
            try {
                wordBean = model.nextWord();
            } catch (Exception ex) {
                view.showJOptionPane("没有更多数据了！");
                return;
            }
            if (wordBean == null) {
                view.showJOptionPane("识别失败");
                return;
            }

            view.setMatrixView(wordBean);
            view.setIdentifyAreaValue(model.getWordBeanName(wordBean));
            System.out.println(System.currentTimeMillis() + "没有更多数据");
        }
    }

    private class MergeButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            WordBean wordBean = null;
            try {
                wordBean = model.mergeWord();
            } catch (Exception ex) {
                view.showJOptionPane("这行没有更多数据合并了！");
                return;
            }
            if (wordBean == null) {
                view.showJOptionPane("识别失败");
                return;
            }

            view.setMatrixView(wordBean);
            view.setIdentifyAreaValue(model.getWordBeanName(wordBean));
            System.out.println(System.currentTimeMillis() + "数据合并");
        }
    }

    private class OkButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String text = view.getUpdateValue();
            if (text == null || text.isEmpty()) {
                view.showJOptionPane("更新内容为空！");
                return;
            }
            model.updateValue(text);
            view.setUpdateValue("");
            view.actionPerformed();
        }
    }


    //识别字体
    private class RecognizeButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            model.setFontHeight(view.getFontHeight());
            String recognize = model.recognize();
            view.setRecognizeView(recognize);

            System.out.println(System.currentTimeMillis() + "识别字体");
        }
    }

    //添加颜色
    private class AddColorListListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            view.showColorListAddDialog(new ColorCallback() {
                @Override
                public void onColorInput(Integer[] colors) {
                    model.getColorRecords().add(new ColorRecord(colors[0], colors[1], colors[2], colors[3], colors[4], colors[5]));
                    view.flushColorListView(model.getColorRecords());
                }
            });
        }
    }

    private class DeleteColorListListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            model.deleteColorList();
            view.flushColorListView(model.getColorRecords());
        }
    }


    private class FontColorListViewInteraction extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            int selectedIndex = view.getColorListPathViewIndex(e);
            if (selectedIndex == -1) return;
            model.setColorListChecked(selectedIndex);
            view.flushColorListView(model.getColorRecords());
        }
    }

    private class FontFilePathViewInteraction extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            int selectedIndex = view.getFontFilePathViewIndex(e);
            model.setFontFilePathsChecked(selectedIndex);
            view.flushFontPathView(model.getFontFilePaths());
        }
    }

    //添加字体文件路径
    private class AddFontFilePathListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            view.showFileChooserView(new FileChooseCallback() {
                @Override
                public void onFileChoose(String filePath) {
                    view.showRemarkDialog(new FileChooseCallback() {
                        @Override
                        public void onFileChoose(String remark) {
                            model.getFontFilePaths().add(new FontFilePath(filePath, remark));
                            view.flushFontPathView(model.getFontFilePaths());
                        }
                    });
                }
            });
        }
    }

    private class DeleteFontFilePathListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            int selectedIndex = view.getFontFilePathSelectIndex();
            if (selectedIndex < 0 || selectedIndex >= model.getFontFilePaths().size()) {
                view.showJOptionPane("没有选中项");
                return;
            }
            view.showConfirmDialog(new FileChooseCallback() {
                @Override
                public void onFileChoose(String filePath) {
                    model.getFontFilePaths().remove(selectedIndex);
                    view.flushFontPathView(model.getFontFilePaths());
                }
            });
        }
    }


    // 捕捉确认按钮事件
    private class CaptureConfirmButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 获取用户输入
            String[] captureFields = view.getCaptureFields();

            if (model.getScreen() == null) {
                view.showJOptionPane("背景图为空");
                return;
            }

            if (Integer.parseInt(captureFields[0]) >= Integer.parseInt(captureFields[2]) ||
                    Integer.parseInt(captureFields[1]) >= Integer.parseInt(captureFields[3]) ||
                    Integer.parseInt(captureFields[2]) >= model.getScreen().getWidth() ||
                    Integer.parseInt(captureFields[3]) >= model.getScreen().getHeight()) {
                view.showJOptionPane("截图范围错误");
                return;
            }

            // 更新模型数据
            model.setSubScreenRect(ImageUtil.getRect(Integer.parseInt(captureFields[0]), Integer.parseInt(captureFields[1]), Integer.parseInt(captureFields[2]), Integer.parseInt(captureFields[3])));

            view.setSubImage(model.getSubImage());
        }
    }


    private class SubScreenComboBoxListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String selectedOption = view.getSelectedOption();
            for (LiterateSubScreenBean subScreenBean : model.getSubScreenBeans()) {
                if (selectedOption.equals(subScreenBean.getName())) {
                    view.setCaptureFields(subScreenBean.getRect());
                }
            }
        }
    }

    // 捕捉确认按钮事件
    private class CaptureButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            BufferedImage screen = model.getGameScreen();
            if (screen != null) {
                model.getSubScreenBeans().get(0).setRect(ImageUtil.getRect(0, 0, screen.getWidth() - 1, screen.getHeight() - 1));
                view.setScreenImage(screen);
                view.setImageSize(screen.getWidth() + "x" + screen.getHeight());
                view.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            }

        }
    }

    private class ScreenButtonListener extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            view.showFileChooserView(new FileChooseCallback() {
                @Override
                public void onFileChoose(String filePath) {
                    model.setPath(filePath);
                    view.setPath(filePath);

                    try {
                        BufferedImage screen = FileUtil.loadImage(filePath);
                        model.setScreen(screen);
                        model.getSubScreenBeans().get(0).setRect(ImageUtil.getRect(0, 0, screen.getWidth() - 1, screen.getHeight() - 1));
                        view.setScreenImage(screen);
                        view.setImageSize(screen.getWidth() + "x" + screen.getHeight());
                        view.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    } catch (IOException ex) {
                        view.showJOptionPane("路径图片转换错误");
                    }
                }
            });
        }
    }

    public interface FileChooseCallback {
        void onFileChoose(String filePath);
    }

    public interface ColorCallback {
        void onColorInput(Integer[] colors);
    }
}


